<template>
	<view>

		<view class="content">
			<!-- 顶部导航栏 -->
			<u-navbar :fixed="false" :autoBack="true" title="异常处理" :safeAreaInsetTop="true"
				leftIconColor="#fff"></u-navbar>

			<!-- <scroll-view class="scroll-container" scroll-y> -->

			<!-- 异常统计概览 -->
			<view class="stats-overview" style="padding: 10px;">
				<view class="stat-item red">
					<text class="stat-value">{{ unhandledCount }}</text>
					<text class="stat-label">未处理异常</text>
				</view>
				<view class="stat-item yellow">
					<text class="stat-value">{{ handlingCount }}</text>
					<text class="stat-label">处理中异常</text>
				</view>
				<view class="stat-item green">
					<text class="stat-value">{{ resolvedCount }}</text>
					<text class="stat-label">已解决异常</text>
				</view>
				<view class="stat-item blue">
					<text class="stat-value">{{ totalCount }}</text>
					<text class="stat-label">累计异常</text>
				</view>
			</view>

			<view class="filter-bar" style="padding: 0 10px;">
				<view class="filter-item" @click="showStatusPicker = true">
					<text class="filter-text">{{ selectedStatus || '全部状态' }}</text>
					<u-icon name="arrow-down" size="24" class="filter-icon"></u-icon>
				</view>
				<view class="filter-item" @click="showTypePicker = true">
					<text class="filter-text">{{ selectedType || '全部类型' }}</text>
					<u-icon name="arrow-down" size="24" class="filter-icon"></u-icon>
				</view>
			</view>
			<view class="flex-auto" style="padding: 10px;">

				<!-- 异常列表 -->
				<view class="abnormal-list">
					<!-- 异常项 -->
					<view class="abnormal-item" v-for="(item, index) in filteredAbnormals" :key="item.id"
						@click="showAbnormalDetail(item)">
						<view class="item-header">
							<text class="abnormal-type">[{{ item.type }}]</text>
							<text class="abnormal-status" :class="item.status">{{ statusMap[item.status] }}</text>
						</view>

						<view class="item-body">
							<text class="abnormal-desc">{{ item.description }}</text>
							<view class="abnormal-meta">
								<text class="meta-time">{{ item.occurTime }}</text>
								<text class="meta-group">样本组：{{ item.sampleGroup }}</text>
							</view>
						</view>

						<view class="item-footer" v-if="item.handler">
							<text class="handler-info">处理人：{{ item.handler || '未处理' }}</text>
							<text class="handle-time">{{ item.handleTime || '' }}</text>
						</view>
					</view>

					<!-- 空状态 -->
					<view class="empty-state" v-if="filteredAbnormals.length === 0">
						<u-icon name="warning-circle" size="60" color="#ccc"></u-icon>
						<text class="empty-text">暂无符合条件的异常记录</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 状态筛选弹窗 -->
		<u-picker :show="showStatusPicker" :columns="statusColumns" @confirm="handleStatusConfirm"
			@cancel="showStatusPicker = false" title="选择状态"></u-picker>

		<!-- 类型筛选弹窗 -->
		<u-picker :show="showTypePicker" :columns="typeColumns" @confirm="handleTypeConfirm"
			@cancel="showTypePicker = false" title="选择异常类型"></u-picker>
		</scroll-view>

		<!-- 异常详情弹窗 -->
		<u-modal v-model="detailVisible" title="异常详情" :content="''"
			:confirm-text="currentAbnormal.status === 'resolved' ? '关闭' : '标记为已解决'" @confirm="handleAbnormalResolve"
			:show-cancel="currentAbnormal.status !== 'resolved'"
			:cancel-text="currentAbnormal.status === 'pending' ? '标记为处理中' : '取消'" @cancel="handleAbnormalCancel">
			<view class="detail-content">
				<view class="detail-section">
					<text class="section-title">异常信息</text>
					<view class="info-item">
						<text class="info-label">异常类型：</text>
						<text class="info-value">{{ currentAbnormal.type }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">发生时间：</text>
						<text class="info-value">{{ currentAbnormal.occurTime }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">样本组：</text>
						<text class="info-value">{{ currentAbnormal.sampleGroup }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">关联数据：</text>
						<text class="info-value">{{ currentAbnormal.relatedData }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">异常描述：</text>
						<text class="info-value">{{ currentAbnormal.description }}</text>
					</view>
				</view>

				<view class="detail-section">
					<text class="section-title">处理记录</text>
					<view class="handle-record" v-if="currentAbnormal.handleRecord">
						<text class="record-content">{{ currentAbnormal.handleRecord }}</text>
						<view class="record-meta">
							<text class="record-handler">处理人：{{ currentAbnormal.handler || '系统' }}</text>
							<text
								class="record-time">{{ currentAbnormal.handleTime || currentAbnormal.occurTime }}</text>
						</view>
					</view>

					<view class="handle-form" v-if="currentAbnormal.status !== 'resolved'">
						<textarea v-model="handleRecord" placeholder="请输入处理措施和结果..." class="record-input"
							:disabled="currentAbnormal.status === 'handling'"></textarea>
					</view>
				</view>

				<view class="detail-section">
					<text class="section-title">异常判定依据</text>
					<view class="judge-basis">
						<text class="basis-text">{{ currentAbnormal.judgeBasis }}</text>
					</view>
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 异常状态映射
				statusMap: {
					pending: '未处理',
					handling: '处理中',
					resolved: '已解决'
				},

				// 筛选条件（uView 2 使用picker）
				selectedStatus: '', // 选中的状态
				selectedType: '', // 选中的类型
				showStatusPicker: false, // 状态筛选弹窗显示
				showTypePicker: false, // 类型筛选弹窗显示

				// 筛选选项（适配u-picker的columns格式）
				statusColumns: [
					['全部状态', '未处理', '处理中', '已解决']
				],
				typeColumns: [
					['全部类型', '超出控制线', '连续点偏移', '趋势异常', '波动异常']
				],

				// 异常列表数据（实际项目从接口获取）
				abnormalList: [{
						id: 'ABN-20250710-001',
						type: '超出控制线',
						status: 'pending',
						description: '第12组样本均值超出UCL上限，测量值为52.3，UCL为51.5',
						occurTime: '2025-07-10 09:32:15',
						sampleGroup: '第12组',
						relatedData: '均值=52.3, UCL=51.5, 样本值=[51.8, 52.5, 52.6]',
						judgeBasis: 'SPC异常判定规则第1条：单个点超出控制限（UCL/LCL）',
						handler: '',
						handleTime: '',
						handleRecord: ''
					},
					{
						id: 'ABN-20250709-002',
						type: '连续点偏移',
						status: 'handling',
						description: '第5-12组连续8点位于中心线一侧，存在系统性偏移',
						occurTime: '2025-07-09 16:45:30',
						sampleGroup: '第5-12组',
						relatedData: '中心线=50.0，连续8点均值范围=[50.8-51.2]',
						judgeBasis: 'SPC异常判定规则第2条：连续8点位于中心线同一侧',
						handler: '张三',
						handleTime: '2025-07-09 17:10:22',
						handleRecord: '已检查设备校准，发现温度传感器偏差，正在调整...'
					},
					{
						id: 'ABN-20250708-001',
						type: '趋势异常',
						status: 'resolved',
						description: '第3-9组呈现连续上升趋势，均值从49.2升至51.3',
						occurTime: '2025-07-08 14:20:05',
						sampleGroup: '第3-9组',
						relatedData: '趋势斜率=0.32/组，R图无异常',
						judgeBasis: 'SPC异常判定规则第3条：连续6点呈现上升或下降趋势',
						handler: '李四',
						handleTime: '2025-07-08 16:35:10',
						handleRecord: '调整了进料速度，趋势已逆转，后续持续监控正常',
						resolveTime: '2025-07-08 18:00:00'
					}
				],

				// 筛选后的异常列表
				filteredAbnormals: [],

				// 详情弹窗控制
				detailVisible: false,
				currentAbnormal: {},
				handleRecord: ''
			};
		},
		computed: {
			// 统计数据
			totalCount() {
				return this.abnormalList.length;
			},
			unhandledCount() {
				return this.abnormalList.filter(item => item.status === 'pending').length;
			},
			handlingCount() {
				return this.abnormalList.filter(item => item.status === 'handling').length;
			},
			resolvedCount() {
				return this.abnormalList.filter(item => item.status === 'resolved').length;
			}
		},
		onLoad() {
			// 初始化筛选列表
			this.filteredAbnormals = [...this.abnormalList];
		},
		methods: {
			// 状态筛选确认（u-picker回调）
			handleStatusConfirm(e) {
				const statusText = e[0];
				this.showStatusPicker = false;

				// 映射显示文本到实际状态值
				const statusMapReverse = {
					'全部状态': '',
					'未处理': 'pending',
					'处理中': 'handling',
					'已解决': 'resolved'
				};
				this.selectedStatus = statusMapReverse[statusText];
				this.filterAbnormals();
			},

			// 类型筛选确认（u-picker回调）
			handleTypeConfirm(e) {
				const typeText = e[0];
				this.showTypePicker = false;
				this.selectedType = typeText === '全部类型' ? '' : typeText;
				this.filterAbnormals();
			},

			// 筛选异常
			filterAbnormals() {
				this.filteredAbnormals = this.abnormalList.filter(item => {
					const statusMatch = !this.selectedStatus || item.status === this.selectedStatus;
					const typeMatch = !this.selectedType || item.type === this.selectedType;
					return statusMatch && typeMatch;
				});
			},

			// 显示异常详情
			showAbnormalDetail(item) {
				this.currentAbnormal = {
					...item
				};
				this.handleRecord = item.handleRecord || '';
				this.detailVisible = true;
			},

			// 处理异常（标记为已解决）
			handleAbnormalResolve() {
				if (this.currentAbnormal.status === 'resolved') {
					this.detailVisible = false;
					return;
				}

				if (!this.handleRecord.trim()) {
					uni.showToast({
						title: '请输入处理记录',
						icon: 'none'
					});
					return;
				}

				// 更新异常状态（实际项目调用接口）
				const index = this.abnormalList.findIndex(item => item.id === this.currentAbnormal.id);
				if (index !== -1) {
					this.abnormalList[index].status = 'resolved';
					this.abnormalList[index].handleRecord = this.handleRecord;
					this.abnormalList[index].handler = '当前用户'; // 实际为登录用户
					this.abnormalList[index].handleTime = this.formatTime(new Date());
					this.abnormalList[index].resolveTime = this.formatTime(new Date());

					// 更新筛选列表
					this.filteredAbnormals = [...this.abnormalList];
					this.detailVisible = false;
					uni.showToast({
						title: '已标记为已解决',
						icon: 'success'
					});
				}
			},

			// 取消或标记为处理中
			handleAbnormalCancel() {
				if (this.currentAbnormal.status === 'pending') {
					// 从"未处理"转为"处理中"
					const index = this.abnormalList.findIndex(item => item.id === this.currentAbnormal.id);
					if (index !== -1) {
						this.abnormalList[index].status = 'handling';
						this.abnormalList[index].handler = '当前用户';
						this.abnormalList[index].handleTime = this.formatTime(new Date());
						this.abnormalList[index].handleRecord = this.handleRecord || '已开始处理';

						// 更新筛选列表
						this.filteredAbnormals = [...this.abnormalList];
						this.detailVisible = false;
						uni.showToast({
							title: '已标记为处理中',
							icon: 'success'
						});
					}
				} else {
					// 关闭弹窗
					this.detailVisible = false;
				}
			},

			// 格式化时间
			formatTime(date) {
				const y = date.getFullYear();
				const m = (date.getMonth() + 1).toString().padStart(2, '0');
				const d = date.getDate().toString().padStart(2, '0');
				const h = date.getHours().toString().padStart(2, '0');
				const mi = date.getMinutes().toString().padStart(2, '0');
				const s = date.getSeconds().toString().padStart(2, '0');
				return `${y}-${m}-${d} ${h}:${mi}:${s}`;
			}
		}
	};
</script>

<style scoped lang="scss">
	/* 滚动容器 */
	.scroll-container {
		flex: 1;
		overflow-y: auto;
		padding-top: 88rpx;
		/* 适配导航栏高度 */
		box-sizing: border-box;
	}


	/* 统计概览 */
	.stats-overview {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr 1fr;
		gap: 24rpx;
		margin-bottom: 32rpx;
	}

	.stat-item {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		text-align: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.stat-item.red {
		border-left: 6rpx solid #f5222d;
	}

	.stat-item.yellow {
		border-left: 6rpx solid #faad14;
	}

	.stat-item.green {
		border-left: 6rpx solid #52c41a;
	}

	.stat-item.blue {
		border-left: 6rpx solid #1890ff;
	}

	.stat-value {
		font-size: 40rpx;
		font-weight: bold;
		display: block;
		margin-bottom: 8rpx;
	}

	.stat-item.red .stat-value {
		color: #f5222d;
	}

	.stat-item.yellow .stat-value {
		color: #faad14;
	}

	.stat-item.green .stat-value {
		color: #52c41a;
	}

	.stat-item.blue .stat-value {
		color: #1890ff;
	}

	.stat-label {
		font-size: 24rpx;
		color: #666666;
	}

	/* 异常列表 */
	.abnormal-list {
		background-color: #ffffff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		padding: 32rpx;
		margin-bottom: 32rpx;
	}

	.list-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 32rpx;
		display: block;
	}

	/* 筛选栏（uView 2 适配） */
	.filter-bar {
		display: flex;
		gap: 16rpx;
		margin-bottom: 32rpx;
	}

	.filter-item {
		flex: 1;
		height: 70rpx;
		border: 2rpx solid #e5e6eb;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		font-size: 26rpx;
		color: #333333;
		background-color: #ffffff;
	}

	.filter-icon {
		color: #999999;
	}

	/* 异常项 */
	.abnormal-item {
		border-bottom: 2rpx solid #f0f0f0;
		padding: 24rpx 0;
		cursor: pointer;
	}

	.abnormal-item:last-child {
		border-bottom: none;
	}

	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.abnormal-type {
		font-size: 28rpx;
		font-weight: 500;
		color: #333333;
	}

	.abnormal-status {
		font-size: 24rpx;
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
		font-weight: 500;
	}

	.abnormal-status.pending {
		background-color: #fff1f0;
		color: #f5222d;
	}

	.abnormal-status.handling {
		background-color: #fffbe6;
		color: #faad14;
	}

	.abnormal-status.resolved {
		background-color: #f6ffed;
		color: #52c41a;
	}

	.item-body {
		margin-bottom: 16rpx;
	}

	.abnormal-desc {
		font-size: 26rpx;
		color: #666666;
		line-height: 1.5;
		margin-bottom: 16rpx;
		display: block;
	}

	.abnormal-meta {
		display: flex;
		justify-content: space-between;
		font-size: 22rpx;
		color: #999999;
	}

	.item-footer {
		display: flex;
		justify-content: space-between;
		font-size: 22rpx;
		color: #666666;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 0;
	}

	.empty-text {
		font-size: 26rpx;
		color: #999999;
		margin-top: 24rpx;
	}

	/* 详情弹窗内容 */
	.detail-content {
		padding: 16rpx 0;
	}

	.detail-section {
		margin-bottom: 32rpx;
	}

	.detail-section:last-child {
		margin-bottom: 0;
	}

	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 24rpx;
		display: block;
		padding-bottom: 8rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.info-item {
		display: flex;
		margin-bottom: 20rpx;
		line-height: 1.5;
	}

	.info-label {
		font-size: 26rpx;
		color: #666666;
		width: 160rpx;
		flex-shrink: 0;
	}

	.info-value {
		font-size: 26rpx;
		color: #333333;
		flex: 1;
	}

	.handle-record {
		background-color: #f6f8fa;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 24rpx;
	}

	.record-content {
		font-size: 26rpx;
		color: #333333;
		line-height: 1.5;
		display: block;
		margin-bottom: 16rpx;
	}

	.record-meta {
		display: flex;
		justify-content: space-between;
		font-size: 22rpx;
		color: #999999;
	}

	.handle-form {
		margin-top: 16rpx;
	}

	.record-input {
		width: 100%;
		min-height: 160rpx;
		border: 2rpx solid #e5e6eb;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 26rpx;
		color: #333333;
		box-sizing: border-box;
		resize: vertical;
	}

	.judge-basis {
		background-color: #f6f8fa;
		border-radius: 8rpx;
		padding: 20rpx;
	}

	.basis-text {
		font-size: 24rpx;
		color: #666666;
		line-height: 1.5;
	}
</style>